﻿using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using CCSManager.CCS;
using Microsoft.Windows.Controls;

namespace CCSManager
{
    /// <summary>
    /// Interaction logic for Products.xaml
    /// </summary>
    public partial class Products : UserControl
    {
        public Products()
        {
            InitializeComponent();
        }

        public void Refresh()
        {
            _ClearAddNewApp();
            _ReloadTeamGrid();
            _ReloadProductGrid();
        }

        private void _ReloadTeamGrid()
        {
            if (App.DeveloperToken != Guid.Empty)
            {
                var ccsWebService = new CCS.CCS();
                var users = ccsWebService.GetTeamMembers(App.Credentials, App.DeveloperToken);
                teamDataGrid.ItemsSource = users;
            }
        }

        private void _HandleVersionTextBoxTextChange(TextBox textBox)
        {
            string value = textBox.Text;
            MatchCollection numberMatch = Regex.Matches(value, "\\d*");
            if (numberMatch.Count > 0)
            {
                string[] matchValues = numberMatch.Cast<Match>().Select(m => m.Value).ToArray();
                textBox.Text = string.Join(string.Empty, matchValues);
            }
        }

        private void _HandleVersionTextBoxFocus(TextBox textBox)
        {
            textBox.SelectAll();
        }

        private void _HandleVersionTextBoxLostFocus(TextBox textBox)
        {
            if (string.IsNullOrEmpty(textBox.Text))
            {
                textBox.Text = 0.ToString();
            }
        }

        #region Text field event handlers

        private void majorVersionTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            _HandleVersionTextBoxFocus(((TextBox)sender));
        }

        private void minorVersionTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            _HandleVersionTextBoxFocus(((TextBox)sender));
        }

        private void buildTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            _HandleVersionTextBoxFocus(((TextBox)sender));
        }

        private void revisionTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            _HandleVersionTextBoxFocus(((TextBox)sender));
        }

        private void licensesTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            _HandleVersionTextBoxFocus(((TextBox)sender));
        }

        private void trialTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            _HandleVersionTextBoxFocus(((TextBox)sender));
        }

        private void majorVersionTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            _HandleVersionTextBoxTextChange(((TextBox)sender));
        }

        private void minorVersionTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            _HandleVersionTextBoxTextChange(((TextBox)sender));
        }

        private void buildTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            _HandleVersionTextBoxTextChange(((TextBox)sender));
        }

        private void revisionTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            _HandleVersionTextBoxTextChange(((TextBox)sender));
        }

        private void majorVersionTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            _HandleVersionTextBoxLostFocus(((TextBox)sender));
        }

        private void minorVersionTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            _HandleVersionTextBoxLostFocus(((TextBox)sender));
        }

        private void buildTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            _HandleVersionTextBoxLostFocus(((TextBox)sender));
        }

        private void revisionTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            _HandleVersionTextBoxLostFocus(((TextBox)sender));
        }

        private void licensesTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            _HandleVersionTextBoxLostFocus(((TextBox)sender));
        }

        private void licensesTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            _HandleVersionTextBoxTextChange(((TextBox)sender));
        }

        private void trialTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            _HandleVersionTextBoxLostFocus(((TextBox)sender));
        }

        private void trialTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            _HandleVersionTextBoxTextChange(((TextBox)sender));
        }

        #endregion

        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            var ccsWebService = new CCS.CCS();
            int licensesPerInvoice = int.Parse(licensesTextBox.Text);
            int trialLengthInDays = int.Parse(trialTextBox.Text);
            string version = string.Format("{0}.{1}.{2}.{3}", majorVersionTextBox.Text, minorVersionTextBox.Text, buildTextBox.Text, revisionTextBox.Text);
            DateTime releaseDate = releaseDatePicker.SelectedDate != null ? releaseDatePicker.SelectedDate.Value : DateTime.Now;
            if (ccsWebService.AddApplication(App.DeveloperToken, appNameTextBox.Text, version, releaseDate, licensesPerInvoice, trialLengthInDays))
            {
                appNameTextBox.Text = string.Empty;
                majorVersionTextBox.Text = 0.ToString();
                minorVersionTextBox.Text = 0.ToString();
                buildTextBox.Text = 0.ToString();
                revisionTextBox.Text = 0.ToString();
                releaseDatePicker.SelectedDate = null;
                licensesTextBox.Text = 0.ToString();
                trialTextBox.Text = 0.ToString();
                _ReloadProductGrid();
            }
        }

        private string teamLabelContent = "(Please select a team from the Active Team list above)";

        private void _ReloadProductGrid()
        {
            if (App.DeveloperToken != Guid.Empty)
            {
                teamLabelContent = teamLabel.Content.ToString();
                teamLabel.Content = App.DeveloperToken.ToString();
                var ccsWebService = new CCS.CCS();
                DeveloperApplication[] apps = ccsWebService.GetProducts(App.DeveloperToken);
                var appsProjected = apps.Select(a => new
                {
                    a.ID,
                    a.Name,
                    Version = string.Join(".", a.Version.Select(v => v.ToString()).ToArray()),
                    a.TrialLengthInDays,
                    a.LicensesPerInvoice,
                    Activations = a.Activations.Count(),
                    Exceptions = a.Exceptions.Count(),
                    Issues = a.Issues.Count(),
                    Registrations = a.Registrations.Count()
                });
                productDataGrid.ItemsSource = appsProjected.ToList();
            }
        }

        public event EventHandler<ProductSelectedEventArgs> ProductSelected;

        private void productDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var dg = ((DataGrid)sender);
            var application = dg.SelectedItem;
            if (application != null && ProductSelected != null)
            {
                var ccsWebService = new CCS.CCS();
                DeveloperApplication[] apps = ccsWebService.GetProducts(App.DeveloperToken);
                Guid productId = new Guid(application.GetType().GetProperties().Where(p => p.Name == "ID").First().GetValue(application, null).ToString());
                ProductSelected(this, new ProductSelectedEventArgs(apps.First(a => a.ID == productId)));
            }
        }

        private ComboBoxItem defaultItem;

        private void activeTeamComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox activeTeamComboBox = ((ComboBox)sender);
            if (activeTeamComboBox.SelectedIndex != -1)
            {
                if (activeTeamComboBox.SelectedItem.ToString().Contains("-"))
                {
                    Guid devToken = new Guid(activeTeamComboBox.SelectedItem.ToString());
                    if (devToken != Guid.Empty)
                    {
                        App.DeveloperToken = devToken;
                        Refresh();
                    }
                }
            }
        }

        private void activeTeamComboBox_DropDownClosed(object sender, EventArgs e)
        {
            ComboBox activeTeamComboBox = ((ComboBox)sender);
            if (activeTeamComboBox.SelectedIndex == -1)
            {
                activeTeamComboBox.ItemsSource = null;
                activeTeamComboBox.Items.Insert(0, new ComboBoxItem { Content = defaultItem.Content, IsSelected = true });
            }
        }

        private void activeTeamComboBox_DropDownOpened(object sender, EventArgs e)
        {
            var ccsWebService = new CCS.CCS();
            var devTokens = ccsWebService.GetDevToken(App.UserKey, App.Credentials);
            if (activeTeamComboBox.SelectedItem is ComboBoxItem)
            {
                defaultItem = new ComboBoxItem { Content = ((ComboBoxItem)activeTeamComboBox.SelectedItem).Content, IsSelected = true };
                activeTeamComboBox.Items.Clear();
            }
            activeTeamComboBox.ItemsSource = devTokens;
        }

        private void addTeamMemberButton_Click(object sender, RoutedEventArgs e)
        {
            var ccsWebService = new CCS.CCS();
            if (ccsWebService.AddTeamMember(App.DeveloperToken, newTeamMemberEmailTextBox.Text))
            {
                Refresh();
            }
        }

        public event EventHandler LogoutRequested;

        private void logoutButton_Click(object sender, RoutedEventArgs e)
        {
            if (LogoutRequested != null)
            {
                LogoutRequested(this, new EventArgs());
            }
        }

        public void Clear()
        {
            activeTeamComboBox.ItemsSource = null;
            activeTeamComboBox.Items.Insert(0, new ComboBoxItem { Content = defaultItem.Content, IsSelected = true });
            productDataGrid.ItemsSource = null;
            teamDataGrid.ItemsSource = null;
            _ClearAddNewApp();
        }

        private void _ClearAddNewApp()
        {
            teamLabel.Content = teamLabelContent;
            appNameTextBox.Text = string.Empty;
            majorVersionTextBox.Text = string.Empty;
            minorVersionTextBox.Text = string.Empty;
            buildTextBox.Text = string.Empty;
            revisionTextBox.Text = string.Empty;
            releaseDatePicker.SelectedDate = null;
            licensesTextBox.Text = string.Empty;
            trialTextBox.Text = string.Empty;
        }
    }

    public class ProductSelectedEventArgs : EventArgs
    {
        public ProductSelectedEventArgs(DeveloperApplication application)
        {
            Application = application;
        }

        public DeveloperApplication Application { get; private set; }
    }
}